package com.zxy.service.impl;

import cn.hutool.core.lang.Assert;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zxy.common.result.Result;
import com.zxy.config.util.JwtUtils;
import com.zxy.config.util.SaltUtils;
import com.zxy.controller.dto.UserDTO;
import com.zxy.entity.User;
import com.zxy.mapper.UserMapper;
import com.zxy.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author zxy
 * @since 2021-04-21
 */
@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    private final UserMapper userMapper;
    private final JwtUtils jwtUtils;

    @Override
    public Result register(User user) {
        System.out.println("user = " + user);
        // 接收用户进来的参数，设置用户的密码进行加密
        // 盐值
        String salt = SaltUtils.getSalt(8);
        Md5Hash md5Hash = new Md5Hash(user.getPassword(), salt, 1024);
        user.setPassword(md5Hash.toHex());
        user.setSalt(salt);
        user.setCreatetime(new Date());
        userMapper.insert(user);
        UserDTO userDTO = new UserDTO();
        BeanUtils.copyProperties(user, userDTO);
        return Result.succ(userDTO);
    }

    @Override
    public Result login(User user, HttpServletResponse response) {
        User result = userMapper.selectOne(new QueryWrapper<User>().eq("username", user.getUsername()));
        Assert.notNull(result, "该用户不存在");
        String password = new Md5Hash(user.getPassword(), result.getSalt(), 1024).toHex();
        System.out.println("password = " + password);
        if (!result.getPassword().equals(password)) {
            return Result.fail("密码不正确，请检查后重新输入");
        }
        // 生成token
        String token = jwtUtils.generateToken(result.getId());
        response.setHeader("Authorization", token);
        UserDTO userDTO = new UserDTO();
        BeanUtils.copyProperties(user, userDTO);
        return Result.succ(userDTO);
    }
}
